package com.hbmcc.heshenghuo.util

import android.content.Context
import android.graphics.Typeface
import android.text.Spannable
import android.text.SpannableStringBuilder
import androidx.databinding.BindingAdapter
import android.widget.TextView
import android.text.style.AbsoluteSizeSpan
import android.text.style.StyleSpan
import com.hbmcc.heshenghuo.R

/**
 * @author 支豪亮
 * @date 2021/8/12 4:21 下午
 * @des TextView dataBinding 适配器
 */
object TextViewAttrAdapter {

    @BindingAdapter(value = ["value", "unit"], requireAll = false)
    @JvmStatic
    fun setTitle(textView: TextView, value: String?, unit: String?) {
        textView.text = setBottomAlignment(value ?: "", unit ?: "", textView.context)
    }


    fun setBottomAlignment(num: String, unit: String, context: Context): SpannableStringBuilder {
        val spanString = SpannableStringBuilder(num + unit) //绝对尺寸
        val absoluteSizeSpanBig = AbsoluteSizeSpan(context.resources.getDimension(R.dimen.sp_20).toInt())
        val absoluteSizeSpanSmall = AbsoluteSizeSpan(context.resources.getDimension(R.dimen.sp_10).toInt())

        var index = num.indexOf(".")
        if (index == -1) index = num.length
        if (num == "--") {
            spanString.setSpan(StyleSpan(Typeface.NORMAL), 0, spanString.length, Spannable.SPAN_INCLUSIVE_INCLUSIVE) // 字体颜色
        } else {
            spanString.setSpan(StyleSpan(Typeface.BOLD), 0, index, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
            spanString.setSpan(StyleSpan(Typeface.NORMAL), index, spanString.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
        }


        spanString.setSpan(absoluteSizeSpanBig, 0, index, Spannable.SPAN_INCLUSIVE_INCLUSIVE) // 字体颜色
        spanString.setSpan(absoluteSizeSpanSmall, index, spanString.length, Spannable.SPAN_INCLUSIVE_INCLUSIVE) // 字体颜色
        return spanString
    }

}